package com.zx.centers.socketservice.client;

import com.zx.centers.socketservice.codec.RpcDecoder;
import com.zx.centers.socketservice.codec.RpcEncoder;
import com.zx.centers.socketservice.dto.IMMessage;
import com.zx.centers.socketservice.dto.IMUser;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

import java.io.IOException;
import java.util.Scanner;

public class Client2 implements Runnable{

    private ClientHandler clientHandler = new ClientHandler();

    public static void main(String[] args) throws IOException {
        new Client2().start();
    }

    public void start() throws IOException {
        new Thread(this).start();
        runServerCMD();
    }

    public void sendMsg(IMMessage msg) throws IOException {
        clientHandler.sendMsg(msg);
    }

    /**
     * 启动客户端控制台
     */
    private void runServerCMD() throws IOException {
        IMUser sender = new IMUser("456","你是猪","1");
        IMUser reciever = new IMUser("123","你是猪","1");
        IMMessage message = new IMMessage(
                "1",
                "1",
                sender,
                "23",
                reciever,
                "你好1",
                "",
                null);
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        do {
            message.setMsg(scanner.nextLine());
        }
        while (clientHandler.sendMsg(message));
    }

    @Override
    public void run() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4))
                            .addLast("encoder", new LengthFieldPrepender(4, false))
                            .addLast(new RpcDecoder(IMMessage.class))
                            .addLast(new RpcEncoder(IMMessage.class))
                            .addLast(clientHandler);
                }
            });
            ChannelFuture f = b.connect("localhost", 9090).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
